package net.liteheaven.xblib.plugin;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import dalvik.system.DexClassLoader;

/**
 * 插件加载帮助类
 *
 * Created by LiangYu on 16/8/29
 */
public class XPluginLoadHelper {

    private static String getDexOutDir(Context ctx){
        return ctx.getDir("optimizedDirectory", Context.MODE_PRIVATE).getAbsolutePath();
    }

    private static String getLibOutDir(Context ctx){
        return ctx.getDir("librarySearchPath", Context.MODE_PRIVATE).getAbsolutePath();
    }

    private static DexClassLoader getClassLoader(Context activity, String apkPath){
        DexClassLoader classLoader = new DexClassLoader(apkPath, getDexOutDir(activity), getLibOutDir(activity), activity.getClassLoader());
        activity.getClassLoader();
        return classLoader;
    }

    public static XPlugin getPlugin(XProxyActivity ctx){
        Intent intent = ctx.getIntent();

        String pluginActivityName;
        try{
            pluginActivityName = intent.getStringExtra(XActivityUtil.PLUGIN_ACTIVITY_NAME);
        }catch (Exception e){
            // case 1.直接调用。活动名无效，尝试加载controller
            return null;
        }

        String pluginPath = "";
        try{
            pluginPath = intent.getStringExtra(XActivityUtil.PLUGIN_PATH);
        }catch (Exception e){
        }

        ClassLoader classLoader;
        // case 2. 反射调用本地APK。无路径，直接从本地加载插件活动类
        if (TextUtils.isEmpty(pluginPath)){
            classLoader = ctx.getClassLoader();
        }else{
            // case 3. 插件方式。有路径，从插件路径加载插件活动类
            try {
                classLoader = XPluginLoadHelper.getClassLoader(ctx, pluginPath);
            } catch (Exception e) {
                throw new IllegalArgumentException("找不到插件");
            }
        }

        XPlugin bean = new XPlugin.Builder()
                .setApkPath(pluginPath)
                .setActivityName(pluginActivityName)
                .setClassLoader(classLoader)
                .build();
        return bean;
    }
}
